
#include "ActionCtrl.h"
#include <Arduino.h>
#include "global.h"
#include "SensorData.h"
#include "blefunc.h"

int BPW_PUMP_PIN = 7;

int BPW_PUMP2_PIN = 6;

// 8:绿色  9：蓝色  10：红色（pin）
int RED_LIGHT_PIN = 10;
int GREEN_LIGHT_PIN = 8;
int BLUE_LIGHT_PIN = 9;
// int BEEP_PIN = 19;
int BEEP_PIN = 21;

long beepCount = 0;

long blinkTimeValue = 0;
String blinkColor = "";

int beepTriggerLevel = 0;

bool disablePump = false;

bool beepTimesOn = false;

bool canDisablePump = false;
bool disableLight = false;

bool disableBeep = false;

// long pumpTimeVal = 0;   // 水泵开启时间

long pumpTimeValue = 0; // 水泵开启时长（秒）

bool isPumpVal = false; // 水泵是否开启

long pumpTimeCounter = 0;
bool isPumpPauseVal = true;
bool isPumpStopVal = true;

bool isPumpContinueVal = false;

int blinkFrequency = 1; // 默认闪烁频率1秒

bool isClickButtonVal = false;

bool isNormalVal = false;

// long getLastPumpTime()
// {
//     return pumpTimeVal;
// }

bool isPumpPause()
{
    return isPumpPauseVal;
}

bool isPumpStop()
{
    return isPumpStopVal;
}

void setPumpStop(bool b)
{

    isPumpStopVal = b;

    if (b)
    {
        closePump();
    }
}

void closePump()
{
    printStr("水泵关闭 closePump");
    removeGlobalTimerCallBack("pump");
    pump(false);
    pumpTimeCounter = 0;
    setPumpPause(true);

    canclePumpPause();
}

void setPumpPause(bool b)
{
    isPumpPauseVal = b;
}

void pumpCounterplus()
{
    pumpTimeCounter++;
   // printStr("pumpTimeCounter++", pumpTimeCounter);
}

long getPumpCounter()
{
    return pumpTimeCounter;
}

long getPumpTime()
{
    return pumpTimeValue;
}

void BeepTimerCallBack(String time)
{
    long t = time.toInt() - 1;
    bool on = t % 2 == 0 ? true : false;

    beep(on);
    if (t >= beepCount)
    {
        beepCount = 0;
        beep(false);
        removeGlobalTimerCallBack("beep");
        beepTimesOn = false;
    }
}

long startTime = 0;

void pumpCallBack(String time)
{

    if (getPumpTime() <= 0)
    {
        printStr("水泵开启时间为零");
        removeGlobalTimerCallBack("pump");
        return;
    }
    if (getPumpCounter() >= pumpTimeValue)
    {
        setPumpStop(true);
        removeGlobalTimerCallBack("pump");
        return;
    }

    if (isPump())
    {
        pumpCounterplus();
    }
    long t_pumpTime = getIntervalPumpTime();
    long t_pauseTime = getIntervalPauseTime();

    long elapsed_time = millis() - startTime;
    if (!isPumpPause()) // 如果水泵开启
    {
        if (elapsed_time >= t_pumpTime * 1000)
        {
            setPumpPause(true); // 如果间隔大于开启时间，暂停
        }
    }
    else
    {
        if (elapsed_time - t_pumpTime * 1000 >= t_pauseTime * 1000)
        {
            setPumpPause(false); // 开启
            //  startTime = millis() - (elapsed_time - t_pumpTime*1000)
            startTime = millis();
        }
    }

    if (getPumpCounter() >= getPumpTime())
    {
        setPumpStop(true);
        FuncCallBack1 f = getGlobalFuncCallBack("pumpFinish");
        if (f != nullptr)
        {
            f(nullptr);
        }
        removeGlobalTimerCallBack("pump");
    }
}

void blinkCallBack(String time)
{
    long t = time.toInt() - 1;
    bool on = t % blinkFrequency == 0 ? true : false;
    light(blinkColor, on);
    if (t >= blinkTimeValue)
    {
        blinkTimeValue = 0;
        removeGlobalTimerCallBack("blink");
        light(blinkColor, false);
    }
}

void beepTimes(long time)
{
    beepTimesOn = true;
    beepCount = time * 2;
    removeGlobalTimerCallBack("beep");
    addGlobalTimerCallBack("beep", BeepTimerCallBack);
}

void setBeepPin(int pin)
{
    BEEP_PIN = pin;
}
void setBeepTriggerLevel(int triggerLevel)
{
    beepTriggerLevel = triggerLevel;
}
bool isBeep()
{

    if (beepTimesOn)
    {
        return true;
    }

    if (beepTriggerLevel == HIGH)
    {
        return digitalRead(BEEP_PIN) == HIGH;
    }
    else
    {
        return digitalRead(BEEP_PIN) == LOW;
    }
}
void closeBeep()
{
    beepCount = 0;
    beep(false);
    removeGlobalTimerCallBack("beep");
    beepTimesOn = false;
}
void beep(bool on)
{
    if (disableBeep)
    {
        on = false;
    }
    int level;
    if (beepTriggerLevel == LOW)
    {
        level = on ? 0 : 1;
    }
    else
    {
        level = on ? 1 : 0;
    }

    digitalWrite(BEEP_PIN, level);
}

void setDisableLight(bool b)
{
    disableLight = b;
}

void delay2(String s);
bool onVal;
void delay1(String s)
{
    pump2(onVal);
    // isPumpVal = onVal;//这里改了之后不知道有没有问题，待测试
}
void delay2(String s)
{

    isPumpVal = onVal;
}

void pump(bool on)
{
    if (isPumpVal == on)
    {
        return;
    }
    isPumpVal = on;
    if (on)
    {
        printStr("水泵开启");
    }
    else
    {
        printStr("水泵关闭");
    }

    onVal = on;
    isPumpVal = on; // 这里改了之后不知道有没有问题，待测试

    if (!on)
    {
        isPumpVal = false;
        setPumpIdle(false);
        setPumpOverload(false);
    }
    if (on)
    {
        pump1(on);

        if (getCurrentVcc() >= 0.5)
        {
            excuteDelay(2, "pump2", delay1);
        }
    }
    else
    {
        pump1(false);
        excuteDelay(1, "pump2", delay1);

    }
}

void pump1(bool on)
{
    if (disablePump && canDisablePump)
    {
        return;
    }
    int level = on ? 1 : 0;
    digitalWrite(BPW_PUMP_PIN, level);
}

void switchRandomPump()
{
    if (!isPump())
    {
        return;
    }
    unsigned long seed = analogRead(A0);
    float randomValue = random(0, 2);

    // 将浮点数转换为整数（0或1）
    int level = int(randomValue);

    if (level == 1)
    {
        pump1(false);
        pump2(true);
    }
    else
    {
        pump1(true);
        pump2(false);
    }
}

void switchPump()
{
    if (!isPump())
    {
        return;
    }

    int level = digitalRead(BPW_PUMP_PIN);
    // bool on1 = level == HIGH ? LOW : HIGH;

    if (level == 1)
    {
        pump1(false);
        pump2(true);
    }
    else
    {
        pump1(true);
        pump2(false);
    }

    printStr("交换水泵");
}

void pump2(bool on)
{
    if (disablePump && canDisablePump)
    {
        return;
    }
    int level = on ? 1 : 0;
    digitalWrite(BPW_PUMP2_PIN, level);
}

void setDisablePump(bool disable)
{
    disablePump = disable;
}

void setCanDisablePump(bool b)
{
    canDisablePump = b;
}

void togglePump()
{

    printStr("togglePump");
    setPumpContinue(!isPumpContinue());
}

// 启动水泵
void pumpTime(long second)
{
    if(second==0){
        printStr("水泵时间为0，直接返回");
        return;
    }
    pumpTimeValue = second;
    pumpTimeCounter = 0;
    addGlobalTimerCallBack("pump", pumpCallBack);
    pump(true);
    setPumpPause(false);
    setPumpStop(false);
    startTime = millis();
}
void pumpTimeContinueCallback(String s)
{
    setPumpContinue(false);
}

bool isPumpContinue()
{
    return isPumpContinueVal;
}

void setPumpContinue(bool b)
{
    isPumpContinueVal = b;
    setPumpPause(!b);
    pump(b);
}

void pumpTimeContinue(long time)
{
    pump(true);
    setPumpContinue(true);
    excuteDelay(time, "continuePump", pumpTimeContinueCallback);
}

void pausePumpTimeCallback(String s)
{
    setPumpPause(false);
}

void pumpPauseTime(long time)
{
    if (time <= 0)
    {
        return;
    }
    setPumpPause(true);
    excuteDelay(time, "pumpPause", pausePumpTimeCallback);
}

void canclePumpPause()
{

    cancelExcuteDelay("pumpPause");
}

void pumpTime1(long second)
{
    // addGlobalTimerCallBack1("pump", pumpCallBack);
    // pump(true);
}

void closeRGB()
{
    digitalWrite(RED_LIGHT_PIN, HIGH);
    digitalWrite(BLUE_LIGHT_PIN, HIGH);
    digitalWrite(GREEN_LIGHT_PIN, HIGH);
}

void light(String color, bool on)
{
    closeRGB();
    if (disableLight)
    {
        return;
    }

    if (color.equals("y"))
    {
        int val = on ? LOW : HIGH;
        digitalWrite(RED_LIGHT_PIN, val);
        digitalWrite(GREEN_LIGHT_PIN, val);
        return;
    }

    int pin = 0;
    if (color.equals("r"))
    {
        pin = RED_LIGHT_PIN;
    }
    else if (color.equals("g"))
    {
        pin = GREEN_LIGHT_PIN;
    }
    else if (color.equals("b"))
    {
        pin = BLUE_LIGHT_PIN;
    }
    int val = on ? LOW : HIGH;
    digitalWrite(pin, val);
}

void blink(String color, long time)
{

    blink(color, 2, time);

    // if(blinkColor.equals(color)&&blinkTimeValue!=0){
    //     blinkTimeValue = time;
    //     return;
    // }
    // blinkTimeValue = time;
    // blinkColor = color;
    // if (addGlobalTimerCallBack("blink", blinkCallBack))
    // {
    //     printStr("blink 定时器添加成功");
    // }
}

void blink(String color, int frequecy, long time)
{

    // printStr("color",color);
    // printStr("frequecy",frequecy);
    // printStr("time",time);

    // printStr("blinkColor",blinkColor);
    // printStr("blinkFrequency",blinkFrequency);
    // printStr("blinkTimeValue",blinkTimeValue);

    if (blinkColor.equals(color) && frequecy == blinkFrequency && blinkTimeValue == time)
    {
        blinkTimeValue = time;
        return;
    }
    blinkTimeValue = time;
    blinkColor = color;
    blinkFrequency = frequecy;

    if (addGlobalTimerCallBack("blink", blinkCallBack))
    {
        printStr("blink 定时器添加成功");
    }
}

bool isDisablePump()
{
    return disablePump;
}

bool isPump()
{
    return isPumpVal;
}

void setDisableBeep(bool b)
{
    disableBeep = b;
}

void beepMS(int ms)
{

    printStr("beepMS");
    if (ms > 1000)
    {
        return;
    }
    beep(true);
    delay(ms);
    beep(false);
}

void ctrlPump()
{
    if (!isPumpStop() && !isPumpPause())
    {
        pump(true);
    }
    else if (isPumpContinue() && !isPumpPause())
    {
        pump(true);
    }
    else
    {
        pump(false);
    }
}

void clickButtonCB(String i)
{
    setClickButton(false);
}

void ctrlLight()
{

    if (isAdvertising())
    {
        blink("b", 15 * 60);
        return;
    }

    if (!isActive())
    {
        light("r", true);
        return;
    }

    if (!isWiFiConnected())
    {
        blink("r", 31536000); // 一年
        return;
    }
    if (isSendDataFailed())
    {
        blink("y", 31536000); // 一年
        return;
    }

    if (false)
    {
        blink("r", 15 * 60);
        return;
    }

    if (isClickButton())
    {
        blink("g", 5 * 60);
        return;
    }

    blink("g", 3, 60 * 60 * 24 * 12); // 3秒闪烁一次，持续一年
}

bool isClickButton()
{
    return isClickButtonVal;
}
void setClickButton(bool b)
{
    isClickButtonVal = b;
}

bool isNormal()
{
    return isNormalVal;
}
void setNormal(bool b)
{
    isNormalVal = b;
}

// 定时任务，间隔开启时间
long getIntervalPumpTime()
{
    int t_pumpTime = 0;
    if (getPumpTime() < 10)
    {
        t_pumpTime = 5;
    }
    else if (getPumpTime() >= 10 && getPumpTime() <= 30)
    {
        t_pumpTime = 8;
    }
    else
    {
        t_pumpTime = 12;
    }
    return t_pumpTime;
}

// 定时任务，间隔暂停时间
long getIntervalPauseTime()
{
    int t_pauseTime = 0;
    if (getPumpTime() <= 10)
    {
        t_pauseTime = 5;
    }
    else if (getPumpTime() >= 10 && getPumpTime() <= 30)
    {
        // t_pauseTime = 20;
        t_pauseTime = 5; // 测试改为5
    }
    else
    {
        // t_pauseTime = 30;
        t_pauseTime = 5; // 测试改为5
    }

    return t_pauseTime;
}

long getTotalPumpTime()
{
    float periodCount = getPumpTime() / getIntervalPumpTime() * 1.0f;

    long total = ceil(periodCount) * (getIntervalPumpTime() + getIntervalPauseTime());

    return total;
}

bool isOpenPump()
{
    if (!isPumpStop())
    {
        return true;
    }
    if (isPumpContinue())
    {
        return true;
    }

    return false;
}